<template>
  <div class="app-container" id="Records">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择日期" prop="date">
        <el-date-picker v-model="dateTime" type="month" placeholder="请选择月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="采购会员" prop="productBrand">
        <el-select v-model="queryParams.company" filterable placeholder="请输入供应商" clearable>
          <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="provide">
        <el-input v-model="queryParams.provide" :disabled="provideShow" placeholder="请输入供应商" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:records:add']">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:records:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <div class="textNuM" v-if="this.allMoney > 0">开票总金额：<span class="kpNum"> {{ formatNumber(this.allMoney) }}</span>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" border>
      <el-table-column label="序号" align="center" prop="index" />

      <el-table-column label="产品名称" align="center" prop="product_name" width="180" />
      <el-table-column label="规格" align="center" prop="specs" width="150">
        <template slot-scope="scope">
          {{ scope.row.specs ? scope.row.specs : '' }}
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="model" width="150">
        <template slot-scope="scope">
          {{ scope.row.model ? scope.row.model : '' }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="product_brand" width="150" />
      <el-table-column label="供应商" align="center" prop="provide" width="100" />
      <el-table-column label="买断入库数量" align="center" prop="count" width=" 100">
        <template slot-scope="scope">
          <span class="rightText">{{ scope.row.settlement_mode == '买断' && scope.row.count > 0 ?
      scope.row.count.toFixed(2) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="压库出库数量" align="center" prop="count" width="110">
        <template slot-scope="scope">
          <span class="rightText">{{ scope.row.settlement_mode == '压库' && scope.row.count > 0 ?
      scope.row.count.toFixed(2) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label=" 合计数量" align="center" prop="productPrice" width="110">
        <template slot-scope="scope">
          <span class="rightText">{{ getSingleTotal(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进价" align="center" prop="plarn_price" width="110">
        <template slot-scope="scope">
          <span class="rightText">{{ formatNumber(!isNaN(parseFloat(scope.row.plarn_price)) && scope.row.plarn_price > 0
      ?
      parseFloat(scope.row.plarn_price).toFixed(2) : '') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售价" align="center" prop="plarn_price" width="110">
        <template slot-scope="scope">
          <span class="rightText">{{ formatNumber(!isNaN(parseFloat(scope.row.product_price)) && scope.row.product_price
      > 0 ?
      parseFloat(scope.row.product_price).toFixed(2) : '') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购金额" align="center" prop="price_money" width="110">
        <template slot-scope="scope">
          <span class="rightText"> {{ formatNumber(scope.row.price_money > 0 ?
      scope.row.price_money.toFixed(2) : '')
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="利润" align="center" prop="price_money" width="110">
        <template slot-scope="scope">
          <span class="rightText1"> {{
      formatNumber(!isNaN(parseFloat(scope.row.plarn_price)) && !isNaN(parseFloat(scope.row.product_price)) &&
        scope.row.plarn_price > 0 && scope.row.product_price > 0 ? parseFloat
          ((parseFloat(scope.row.product_price).toFixed(2) -
            parseFloat(scope.row.plarn_price).toFixed(2)) * getSingleTotal(scope.row)).toFixed(2) : '')

    }}</span>
        </template>
      </el-table-column>
      <el-table-column label="营运公司" align="center" prop="company" />
      <el-table-column label="开票类型" align="center" prop="productGroup">
        <template slot-scope="scope">
          <div v-if="selectShow == `productGroup${scope.row.index}`">
            <el-select v-model="value" @change="selectChange(scope.row)">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <span v-else>{{ scope.row.groupList.length !== 0 ? scope.row.groupList[0].productGroup :
      '' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" prop="productGroup" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.groupList.length !== 0" size="mini" type="text"
            @click="cellClick(scope.row, scope.column)" v-hasPermi="['system:records:edit']">修改</el-button>

        </template>
      </el-table-column>
    </el-table>
    <div class="NumAll">
      <div class="textNuM1" v-if="this.allMoney > 0">采购总金额：<span class="kpNum"> {{ formatNumber(this.allMoney) }}</span>
      </div>
      <div class="textNuM1" v-if="this.sumMoney > 0">销售总金额：<span class="kpNum"> {{ formatNumber(this.sumMoney)
          }}</span>
      </div>
      <div class="textNuM1" v-if="this.productPrice > 0">利润总金额：<span class="kpNum"> {{
      formatNumber(parseFloat(this.productPrice).toFixed(2))
    }}</span></div>
    </div>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />



    <!-- 添加或修改开票明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :show-close="false" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库编码" prop="warehouseCode">
          <el-input v-model="form.warehouseCode" placeholder="请输入仓库编码" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="工单号" prop="repairBillCode">
          <el-input v-model="form.repairBillCode" placeholder="请输入工单号" />
        </el-form-item>
        <el-form-item label="车号" prop="busCode">
          <el-input v-model="form.busCode" placeholder="请输入车号" />
        </el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="售价" prop="productPrice">
          <el-input v-model="form.productPrice" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="数量" prop="productCount">
          <el-input v-model="form.productCount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="金额" prop="productMoney">
          <el-input v-model="form.productMoney" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="品牌" prop="productBrand">
          <el-input v-model="form.productBrand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="供应商" prop="provide">
          <el-input v-model="form.provide" placeholder="请输入供应商" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { listRecords, addRecords, group } from "@/api/system/records";

export default {
  name: 'Records',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 开票明细表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      value: "",
      // 是否显示弹出层
      open: false,
      provideShow: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: "",
        productName: "",
        company: "",
        provide: "",
        productGroup: null,

      },
      selectShow: "",
      oldData: {},
      // 表单参数
      form: {},
      // 表单校验
      companyList: [
        { value: '营运公司', label: '营运公司' },
        { value: '崇明巴士', label: '崇明巴士' },
        { value: '金山巴士', label: '金山巴士' }
      ],
      rules: {
        warehouseCode: [
          { required: true, message: '请输入仓库编码', trigger: 'blur' }
        ],
        warehouseName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' }
        ],
        repairBillCode: [
          { required: true, message: '请输入工单号', trigger: 'blur' }
        ],
        busCode: [
          { required: true, message: '请输入车号', trigger: 'blur' }
        ],
        productCode: [
          { required: true, message: '请输入产品编码', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productPrice: [
          { required: true, message: '请输入售价', trigger: 'blur' }
        ],
        productCount: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
        productMoney: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        productBrand: [
          { required: true, message: '请输入品牌', trigger: 'blur' }
        ],
        provide: [
          { required: true, message: '请输入供应商', trigger: 'blur' }
        ]
      },

      options: [
        {
          value: '轮胎',
          label: '轮胎'
        }, {
          value: '润滑油',
          label: '润滑油'
        }, {
          value: '制冷剂',
          label: '制冷剂'
        }, {
          value: '配件',
          label: '配件'
        }
      ],
      deptName: "",
      dateTime: [],
      // 开票总金额
      allMoney: "",
      // 利润总金额
      productPrice: "",
      // 售价总金额
      sumMoney: "",
      fisrtActivate: true
    };
  },

  created() {
    this.eventHnadling();
  },
  activated() {
    if(!this.fisrtActivate) {
      if(this.queryParams.provide!== this.$route.query.provide) {
        this.eventHnadling();
        this.queryParams.pageNum = 1;
      }
    } else {
      // 防止 重复请求
      this.fisrtActivate = false;
    }
  },
  methods: {
    eventHnadling() {
      this.queryParams.provide = this.$route.query.provide;
      this.queryParams.productGroup = this.$route.query.productGroup;
      const User = localStorage.getItem('User');
      this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
      if (this.deptName !== '物资公司') {
        this.queryParams.provide = this.deptName;
        this.provideShow = true;
      } else {
        this.queryParams.provide = "";
        this.provideShow = false;
      }
      this.FormData();
      this.getList();

    },
    /** 查询开票明细列表 */
    getList() {
      this.loading = true;
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      this.queryParams.startTime = this.$route.query.dateTime ? this.$route.query.dateTime : formattedStartDate;
      listRecords(this.queryParams).then(response => {
        this.recordsList = response.rows;
        this.allMoney = response.rows.length > 0 ? response.rows[0].allMoney.toFixed(2) : 0;
        this.sumMoney = response.rows.length > 0 ? response.rows[0].sumMoney.toFixed(2) : 0;
        this.productPrice = response.rows.length > 0 ? response.rows[0].sumMoney.toFixed(2) - response.rows[0].allMoney.toFixed(2) : 0;
        this.recordsList.forEach((item, index) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    getSingleTotal(row) {
      let a = row.settlement_mode == '买断' && row.count > 0 ? row.count.toFixed(2) : '';
      let b = row.settlement_mode == '压库' && row.count > 0 ? row.count.toFixed(2) : '';
      return a + b
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        warehouseCode: null,
        warehouseName: null,
        repairBillCode: null,
        busCode: null,
        productCode: null,
        productName: null,
        productPrice: null,
        plarnPrice: null,
        productCount: null,
        productMoney: null,
        createTime: null,
        productBrand: null,
        provide: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.company = "";
      this.FormData();
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加开票明细";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addRecords(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/records/export', {
        ...this.queryParams
      }, `物资开票明细${this.queryParams.startTime}.xlsx`)
    },
    // 开票类型事件
    cellClick(row, column) {
      this.value = row.groupList.length > 0 ? row.groupList[0].productGroup : '';
      this.selectShow = column.property + row.index;
      this.oldData = row;
    },
    selectChange(row) {
      let params = {
        productCode: row.product_code,
        productGroup: this.value
      }
      group(params).then(rst => {
        if (rst.code === 200) {
          this.selectShow = "";
          this.$message.success(rst.msg);
          this.getList();
        } else {
          this.$message.error(rst.msg);
          this.getList();
        }
      })
    },
    FormData() {
      // 定义一个函数,用于格式化日期为"yyyy-MM"
      const formatDate = date => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      };

      // 获取当前日期
      const currentDate = new Date();
      const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);

      // 设置dateTime的初始值为当前年月,并格式化为"yyyy-MM"
      this.dateTime = this.$route.query.dateTime ? this.$route.query.dateTime : formatDate(lastMonth);;
    },
    formatNumber(value) {
      if (value) {
        let [integerPart, decimalPart] = value.toString().split('.');
        let formattedNumber = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + decimalPart.slice(0, 3);
        return formattedNumber;
      }

    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-button--text {
  font-size: 13px;
}

.rightText {
  float: right;
}

.rightText1 {
  float: right;
  color: red;
}

.NumAll {
  position: absolute;
  z-index: 999;
  margin-top: 10px;
  display: flex;

  .textNuM1 {
    margin-right: 15px;
    font-size: 15px;
    margin-top: 3px;
    color: #c0c4cc;

    .kpNum {
      font-weight: 600;
      color: red;
    }
  }
}

.textNuM {
  float: right;
  margin-right: 15px;
  font-size: 15px;
  margin-top: 3px;
  color: #c0c4cc;

  .kpNum {
    font-weight: 600;
    color: red;
  }
}
</style>
